package org.example.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.model.User;
import org.junit.Test;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class WebUtil {

    private static final ObjectMapper M = new ObjectMapper();

    //需要把消息中的日期，转换为年-月-日 时:分:秒
    static {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        M.setDateFormat(df);
    }

    //服务端上传头像的路径
//    public static final String LOCAL_HEAD_PATH="D:\\Code\\Java\\picture";
    public static final String LOCAL_HEAD_PATH="/root/upload/chatroom";

    //序列化
    public static String write(Object o){
        try{
            return  M.writeValueAsString(o);
        }catch (JsonProcessingException e){
            throw new RuntimeException("转换Java对象为json字符串出错");
        }
    }

    //反序列化
    public static <T> T read(InputStream is,Class<T> clazz){
        try {
            return M.readValue(is,clazz);
        } catch (IOException e) {
            throw new RuntimeException("转换输入流json字符串为java对象出错");
        }
    }
    public static <T> T read(String is,Class<T> clazz){
        try {
            return M.readValue(is,clazz);
        } catch (IOException e) {
            throw new RuntimeException("转换输入流json字符串为java对象出错");
        }
    }

    //获取session中保存的用户信息
    public static User getLoginUser(HttpSession session){
        if (session != null){
            //session不为空，返回session中获取的用户
            //获取时的键，需要与登录时保存的键一致
            return (User)session.getAttribute("user");
        }
        return null;
    }

    @Test
    public void writeTest(){
        User user = new User();
        user.setId(2);
        user.setUsername("王麻子");
        user.setPassword("123");
        user.setNickname("县长");
        System.out.println(write(user));
    }

    @Test
    public void readTest(){
        String s = "{\"id\":2,\"username\":\"王麻子\",\"password\":\"123\",\"nickname\":\"县长\",\"logoutTime\":null}\n";
        System.out.println(read(s, User.class));
    }
}
